package com.wang.concurrency;

public class DrawMoney {

	
	public static void main(String[] args) {
		Runnable r = new DrawRunnable(new Account(800), 300);

		new Thread(r, "甲").start();
		new Thread(r, "乙").start();
	}
	
	
	
	
	private static class DrawRunnable implements Runnable{
		
		private Account account;
		private double money;

		public DrawRunnable(Account account, double money) {
			super();
			this.account = account;
			this.money = money;
		}

		@Override
		public void run() {			
//			同步监视器synchronized
			//推荐使用可能被并发访问的共享资源作为同步监视器.
//			synchronized可以修饰方法,也可以修改代码块,但不能修饰构造器,成员变量等.
//			同步方法锁定的同步监视器是this
				synchronized(account){
					while (true) {
		                if (account.getBalance() > money) {
		                    System.out.println(Thread.currentThread().getName() + "取钱" + money + "成功");
		                    try {
		                        Thread.sleep(1);
		                    } catch (InterruptedException e) {
		                        throw new RuntimeException(e);
		                    }
		                    account.reduceBalance(money);
		                    System.out.println("\t" + Thread.currentThread().getName() + "成功后的余额: " + account.getBalance());
		                } else {
		                    System.out.println(Thread.currentThread().getName() + "取钱失败");
		                    System.out.println("\t" + Thread.currentThread().getName() + "失败后的余额: " + account.getBalance());
		                    break;
		                }
		            }
				}


			
		}
		
		
	}
	
}

